package org.itboys.weixin.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.weixin.constant.WeixinConstants;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.service.WeixinConfigService;
import org.itboys.weixin.service.WeixinCoreService;
import org.itboys.weixin.tools.MessageUtils;
import org.itboys.weixin.tools.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信统一入口
 * 
 * @author
 */
@RestController
public class WeixinGateway extends BaseController {

	private static String GET = "GET";

	@Autowired
	private WeixinCoreService weixinCoreService;
	@Autowired
	private WeixinConfigService weixinConfigService;

	@RequestMapping("/weixin/gateway/{weixinId}")
	public void gateway(HttpServletRequest request,
			HttpServletResponse response,
			@PathVariable("weixinId") Long weixinId) {
		String method = request.getMethod();
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		WeixinConfig weixinConfig = weixinConfigService
				.getById(weixinId);
		String token = weixinConfig.getToken();
		boolean signResult = SignUtil.checkSignature(token, signature,
				timestamp, nonce);// 签名校验
		if (method.equals(GET)) {// 验证的时候微信是get请求
			String echostr = request.getParameter("echostr");
			if (signResult) {
				AjaxUtils.renderText(response, echostr);
			} else {
				AjaxUtils.renderText(response, WeixinConstants.ERROR_REQUEST);
			}
		} else {// 其他时候微信都是post请求
			if (signResult) {
				Map<String, String> param = MessageUtils.xmlToMap(request);
				String responseXml = weixinCoreService.doResponseWeixin(param, weixinConfig);
				// System.out.println("responseXml="+responseXml);
				//AjaxUtils.renderXml(response, responseXml);
			} else {
				//AjaxUtils.renderText(response, WeixinConstants.ERROR_REQUEST);
			}
		}
	}

}
